import { constantRoutes } from '@/router/index'

export default {
  namespaced: true,
  state: {
    routers: constantRoutes
  },
  mutations: {
    setRouters(state, newRouters) {
      state.routers = [...constantRoutes, ...newRouters]
    }
  },
  actions: {
    createNewRoutes(context, payload) {
      function transListToTreeData(list, rootValue) {
        const arr = []
        list.forEach(item => {
          if (item.pid === rootValue) {
            // 找到了匹配的节点
            // 当前节点的id 和 当前节点的子节点的pid是想等的
            const children = transListToTreeData(list, item.id) // 找到的节点的子节点
            if (children.length) item.children = children // 将子节点赋值给当前节点
            arr.push(item)
          }
        })
        return arr
      }

      function loadView(comStr) {
        try {
          if (comStr === 'layout') {
            // 加载layout组件
            // import layout from '@/layout/index.vue  ===  require('@/layout/index.vue').default
            return require('@/layout/index.vue').default
          } else {
            // 直接在 comStr传过来的模块
            return require('@/views/' + comStr + '.vue').default
          }
        } catch (error) {
          return require('@/views/error.vue')
        }
      }
      const newRoutes = payload.map(item => {
        return {

          path: item.route,
          name: item.permission_mark,
          meta: {
            title: item.permission_name,
            icon: item.icon
          },
          hidden: item.hidden !== 1,
          redirect: item.redirect,
          component: loadView(item.component),
          pid: item.parent_id,
          id: item.id
        }
      })
      return transListToTreeData(newRoutes, 0)
    }
  }
}
